import axios, { AxiosProgressEvent, AxiosResponse } from 'axios';

// 定义消息数据接口
interface ChatMessageData {
  message: string;
  conversation_id?: string;
  [key: string]: unknown;
}

// 定义消息列表参数接口
interface MessageListParams {
  conversation_id?: string;
  page?: number;
  page_size?: number;
  [key: string]: unknown;
}

// 发送消息（流式/SSE实现，仅请求指定URL）
export const sendChatMessage = async (
  data: ChatMessageData,
  onMessage: (msg: string) => void,
  bot_id: string
): Promise<string> => {
  const url = 'https://zhi1develop.zicp.fun/v1/chat-messages';
  const response = await axios({
    url,
    method: 'post',
    data,
    responseType: 'text',
    headers: {
      Authorization: 'Bearer ' + bot_id,
      'Content-Type': 'application/json'
    },
    onDownloadProgress: (progressEvent: AxiosProgressEvent) => {
      const chunk = progressEvent.event.target?.responseText || '';
      const lines = chunk.split('\n').filter((line: string) => line.trim() !== '');
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.substring(6));
            if (data.answer || data.message) {
              const newContent = data.answer || data.message || '';
              onMessage(newContent);
            }
          } catch {
            // 忽略解析错误
          }
        }
      }
    }
  });

  return response.data;
};

// 获取消息
export const getMessagesList = (params: MessageListParams, bot_id: string): Promise<AxiosResponse> => {
  return axios({
    url: `https://zhi1develop.zicp.fun/v1/messages`,
    method: 'get',
    params,
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + bot_id
    }
  });
};



